<template>
    <div v-if="!routeItem.hidden&&routeItem.children" class="menu-wrapper">

      <template v-if="hasOneShowingChild(routeItem.children) && !onlyOneChild.children&&!routeItem.alwaysShow">

        <router-link :to="resolvePath(onlyOneChild.path)">
          <el-menu-item :index="resolvePath(onlyOneChild.path)">
            <item v-if="routeItem.meta" :icon="routeItem.meta.icon" :title="routeItem.meta.title" />
          </el-menu-item>
        </router-link>

      </template>
      <el-submenu v-else :index="routeItem.name||routeItem.path">
        <template slot="title">
          <item v-if="routeItem.meta" :icon="routeItem.meta.icon" :title="routeItem.meta.title" />
        </template>

        <template v-for="child in routeItem.children" v-if="!child.hidden">
          <sidebar-item v-if="child.children&&child.children.length>0" :is-nest="true" :routeItem="child" :key="child.path" :base-path="resolvePath(child.path)" class="nest-menu"/>
          
          <router-link v-else :to="resolvePath(child.path)" :key="child.name">
            <el-menu-item-group>
            <el-menu-item :index="resolvePath(child.path)">
              <item v-if="child.meta" :icon="child.meta.icon" :title="child.meta.title" />
            </el-menu-item>
           </el-menu-item-group>
          </router-link>
        </template>
      </el-submenu>
    </div>
</template>

<script>
import Item from "./Item";
import path from "path";

export default {
  components: { Item },
  props: {
    routeItem: {
      type: Object,
      required: true
    },
    isNest: {
      type: Boolean,
      default: false
    },
    basePath: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      onlyOneChild: null
    };
  },
  methods: {
    hasOneShowingChild(children) {
      const showingChildren = children.filter(item => {
        if (item.hidden) {
          return false;
        } else {
          this.onlyOneChild = item;
          return true;
        }
      });
      if (showingChildren.length === 1) {
        return true;
      }
      return false;
    },
    resolvePath(routePath) {
      return path.resolve(this.basePath, routePath);
    },
    isExternalLink(routePath) {
      const urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
      return urlregex.test(routePath);
    }
  }
};
</script>



